package com.gulimall.ware.service.impl;

import com.gulimall.ware.domain.entity.WareSku;
import com.gulimall.ware.mapper.WareSkuMapper;
import com.gulimall.ware.service.IWareSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 商品库存 服务实现类
 * </p>
 *
 * @author 坤哥
 * @since 2025-08-27
 */
@Service
public class WareSkuServiceImpl extends ServiceImpl<WareSkuMapper, WareSku> implements IWareSkuService {
    /**
     * 查询商品库存
     */
    @Override
    public Integer getProductStock(Long skuId) {
        WareSku wareSku = lambdaQuery().eq(WareSku::getSkuId, skuId).one();
        Integer stock = wareSku.getStock();
        Integer stockLocked = wareSku.getStockLocked();
        return stock - stockLocked;
    }

    /**
     * 扣减库存
     */
    @Override
    public void reduceWare(Long skuId, Integer count) {
        WareSku wareSku = lambdaQuery().eq(WareSku::getSkuId, skuId).one();
        if((wareSku.getStock() - wareSku.getStockLocked()) <= 0){//库存不足
            throw new RuntimeException("商品skuId == "+ skuId +"的库存不足");
        }
        //模拟远程调用超时
//        try {
//            Thread.sleep(5000);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        lambdaUpdate().eq(WareSku::getSkuId,skuId).setSql("stock_locked = stock_locked +" + count).update();
    }
}
